/**
* @file LiveViewWindow.h in LiveGraph
* @author linfe
* @comment
* Create on 2022/9/25 23:46
* @version 1.0
**/

#ifndef LIVEGRAPH_SRC_UI_LIVEVIEWWINDOW_H_
#define LIVEGRAPH_SRC_UI_LIVEVIEWWINDOW_H_

#include <qwt_plot_curve.h>
#include "LiveProtocol.h"
#include "Ui_LiveView.h"
#include "SerialPortHandler.h"
#include "qwt.h"
#include <QPointF>
#include <list>
#include <QThread>
#include <QSerialPort>
#include <qwt_plot_grid.h>

QT_BEGIN_NAMESPACE
namespace Ui { class Ui_LiveGraphMain; }
QT_END_NAMESPACE

class LiveViewWindow : public QMainWindow {
Q_OBJECT
public:
    explicit LiveViewWindow(QMainWindow *parent = nullptr);

    ~LiveViewWindow() override;

private:
    void InitUi();

    void ScanHardware();

private:
    Ui_LiveGraphMain *ui;
    QLabel *status;

    QList<QSerialPortInfo> ports;
    /*qwt*/
    QwtPlotCurve *curves[3] = {nullptr, nullptr, nullptr};
    QColor colors[3] = {
            {0xff, 0,    0},
            {1,    0xff, 2},
            {0,    0,    0xff},
    };
    QString titles[3] = {
            "x", "y", "z",
    };
    LiveData data_pre;
    std::list<LiveData> point_data;
    QwtPlotGrid *grid;

    QPolygonF points[3];
    SerialPortHandler handler;
    double cur_xdiv;
    double cur_ydiv;


    QThread *th_serial;

    QTimer *timer;
    uint32_t data_cnt_per_sec = 0;
    const int MAX_SUPPORT_POINTS = 1000;
    uint32_t data_cnt = 0;
    uint32_t data_cnt_pre = 0;
    uint32_t in_valid_data_cnt = 0;
    uint32_t count_cycle = 2;


    bool pause_flag = false;
    signals:
    void SerialControl(bool);

public slots:

    void on_btnConnect_clicked();

    void on_actionClear_triggered();

    void on_actionPause_triggered();

    void on_cbxXDiv_currentIndexChanged(int index);
    void on_cbxYDiv_currentIndexChanged(int index);

    void on_actionStop_triggered();



    void on_DataReady(LiveData data);

    void on_SerialStateChanged(QSerialPort::SerialPortError);

    void on_1secTimer();
};

#endif //LIVEGRAPH_SRC_UI_LIVEVIEWWINDOW_H_
